package com.hd.crdao.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Base64;
import android.util.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class StringUtils {
    public final static String UTF_8 = "utf-8";

    /**
     * @param transferDate 需要转换成日期的时间字符串
     * @return 只显示日期不显示时间
     */
    public static String getDate(String transferDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINESE);
        try {
            Date date = sdf.parse(transferDate);
            return sdf.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 版本控制更新内容时使用
     * 通过"/" 识别换行操作
     *
     * @param words
     * @return
     */
    public static String dealWithWords(String words) {
        if (words != null && !TextUtils.isEmpty(words)) {
            if (words.contains("/")) {
                return words.replace("/", "\n");
            } else {
                return words;
            }
        } else {
            return "";
        }
    }


    public static String getDateWithoutYear(String transferDate) {
        String date = getDate(transferDate);
        String[] split = date != null ? date.split("-") : new String[0];
        return split[0] + "年" + split[1] + "月" + split[2] + "日";

    }

    /**
     * 只用于金额显示，所有前面加了一个人民币符号
     * @param doubleNumber
     * @return
     */
    public static String doubleToString(Double doubleNumber) {
            if(doubleNumber!=null){
                String valueOf = String.valueOf(doubleNumber);
                if(valueOf.contains(".")){
                    if(valueOf.indexOf(".")==valueOf.length()-2){
                        return    "¥"+ valueOf+"0";
                    }else{
                        return  "¥"+ valueOf;
                    }
                }else{
                    return valueOf+".00";
                }

        }
            return "¥0.00";
    }

    /**
     * 判断字符串是否有值，如果为null或者是空字符串或者只有空格或者为"null"字符串，则返回true，否则则返回false
     */
    public static boolean isEmpty(String value) {
        return !(value != null && !"".equalsIgnoreCase(value.trim())
                && !"null".equalsIgnoreCase(value.trim()));
    }

    /**
     * 判断多个字符串是否相等，如果其中有一个为空字符串或者null，则返回false，只有全相等才返回true
     */
    public static boolean isEquals(String... agrs) {
        String last = null;
        for (String str : agrs) {
            if (isEmpty(str)) {
                return false;
            }
            if (last != null && !str.equalsIgnoreCase(last)) {
                return false;
            }
            last = str;
        }
        return true;
    }

    /**
     * 返回一个高亮spannable
     *
     * @param content 文本内容
     * @param color   高亮颜色
     * @param start   起始位置
     * @param end     结束位置
     * @return 高亮spannable
     */
    public static CharSequence getHighLightText(String content, int color,
                                                int start, int end) {
        if (TextUtils.isEmpty(content)) {
            return "";
        }
        start = start >= 0 ? start : 0;
        end = end <= content.length() ? end : content.length();
        SpannableString spannable = new SpannableString(content);
        CharacterStyle span = new ForegroundColorSpan(color);
        spannable.setSpan(span, start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return spannable;
    }

    /**
     * 获取链接样式的字符串，即字符串下面有下划线
     *
     * @param resId 文字资源
     * @return 返回链接样式的字符串
     */
    public static Spanned getHtmlStyleString(int resId) {
        String sb = "<a href=\"\"><u><b>" + UIUtils.getString(resId) +
                " </b></u></a>";
        return Html.fromHtml(sb);
    }

    /**
     * 格式化文件大小，不保留末尾的0
     */
    public static String formatFileSize(long len) {
        return formatFileSize(len, false);
    }

    /**
     * 格式化文件大小，保留末尾的0，达到长度一致
     */
    public static String formatFileSize(long len, boolean keepZero) {
        String size;
        DecimalFormat formatKeepTwoZero = new DecimalFormat("#.00");
        DecimalFormat formatKeepOneZero = new DecimalFormat("#.0");
        if (len < 1024) {
            size = String.valueOf(len + "B");
        } else if (len < 10 * 1024) {
            // [0, 10KB)，保留两位小数
            size = String.valueOf(len * 100 / 1024 / (float) 100) + "KB";
        } else if (len < 100 * 1024) {
            // [10KB, 100KB)，保留一位小数
            size = String.valueOf(len * 10 / 1024 / (float) 10) + "KB";
        } else if (len < 1024 * 1024) {
            // [100KB, 1MB)，个位四舍五入
            size = String.valueOf(len / 1024) + "KB";
        } else if (len < 10 * 1024 * 1024) {
            // [1MB, 10MB)，保留两位小数
            if (keepZero) {
                size = String.valueOf(formatKeepTwoZero.format(len * 100 / 1024
                        / 1024 / (float) 100))
                        + "MB";
            } else {
                size = String.valueOf(len * 100 / 1024 / 1024 / (float) 100)
                        + "MB";
            }
        } else if (len < 100 * 1024 * 1024) {
            // [10MB, 100MB)，保留一位小数
            if (keepZero) {
                size = String.valueOf(formatKeepOneZero.format(len * 10 / 1024
                        / 1024 / (float) 10))
                        + "MB";
            } else {
                size = String.valueOf(len * 10 / 1024 / 1024 / (float) 10)
                        + "MB";
            }
        } else if (len < 1024 * 1024 * 1024) {
            // [100MB, 1GB)，个位四舍五入
            size = String.valueOf(len / 1024 / 1024) + "MB";
        } else {
            // [1GB, ...)，保留两位小数
            size = String.valueOf(len * 100 / 1024 / 1024 / 1024 / (float) 100)
                    + "GB";
        }
        return size;
    }

    /**
     * 解析地址信息
     * 返回的是带逗号的地址信息,需要手动replace逗号
     *
     * @return 带逗号的地址信息
     */
    public static String ParseAddress(String targetAddress) {
        String provinceCityArea;
        String detailAddress;
        if (targetAddress.contains("区")) {
            provinceCityArea = targetAddress.substring(0, targetAddress.indexOf("区") + 1);
            detailAddress = targetAddress.substring(targetAddress.indexOf("区") + 1, targetAddress.length());
        } else if (targetAddress.contains("县")) {
            provinceCityArea = targetAddress.substring(0, targetAddress.indexOf("县"));
            detailAddress = targetAddress.substring(targetAddress.indexOf("县") + 1, targetAddress.length());
        } else {        //表明没有城市区域,
            provinceCityArea = "";
            detailAddress = targetAddress;
        }
        return provinceCityArea + "," + detailAddress;

    }


    public static String TransferTOString(String[] array) {
        String result = "";
        if (array != null && array.length > 0) {
            for (String content : array) {
                if (!TextUtils.isEmpty(content)) {
                    result.concat(content + ",");
                }
            }
            return result.substring(0, result.length() - 1);
        }
        return null;
    }


    public static class Sputils {
        private static final String SCENE_LIST = "SCENE_LIST";

        public static String SceneList2String(List SceneList) throws IOException {
            // 实例化一个ByteArrayOutputStream对象，用来装载压缩后的字节文件。
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            // 然后将得到的字符数据装载到ObjectOutputStream
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                    byteArrayOutputStream);
            // writeObject 方法负责写入特定类的对象的状态，以便相应的 readObject 方法可以还原它
            objectOutputStream.writeObject(SceneList);
            // 最后，用Base64.encode将字节文件转换成Base64编码保存在String中
            String SceneListString = new String(Base64.encode(
                    byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
            // 关闭objectOutputStream
            objectOutputStream.close();
            return SceneListString;
        }

        @SuppressWarnings("unchecked")
        public static List String2SceneList(String SceneListString)
                throws IOException,
                ClassNotFoundException {
            byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
                    Base64.DEFAULT);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                    mobileBytes);
            ObjectInputStream objectInputStream = new ObjectInputStream(
                    byteArrayInputStream);
            List SceneList = (List) objectInputStream.readObject();
            objectInputStream.close();
            return SceneList;
        }

        public static void savelist(Context mcontext, List<String> mlist) {
            List mList;
            SharedPreferences mySharedPreferences = mcontext.getSharedPreferences(
                    "scenelist", Context.MODE_PRIVATE);
            SharedPreferences.Editor edit = mySharedPreferences.edit();
            try {
                String liststr = SceneList2String(mlist);
                edit.putString(SCENE_LIST, liststr);
                edit.commit();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public static List<String> getList(Context mcontext) {
            List mList = null;
            SharedPreferences sharedPreferences = mcontext.getSharedPreferences(
                    "scenelist", Context.MODE_PRIVATE);
            String liststr = sharedPreferences.getString(SCENE_LIST, "");
            try {
                mList = String2SceneList(liststr);
            } catch (ClassNotFoundException | IOException e) {
                e.printStackTrace();
            }
            Log.i("PIC", mList != null ? mList.toString() : null);
            return mList;

        }
    }
}
